package cn.itcast.bos.web.action.take_delivery;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.domain.take_delivery.Promotion;
import cn.itcast.bos.service.take_delivery.PromotionService;
import cn.itcast.bos.web.action.common.BaseAction;

/**
 * 
 * @author Administrator
 *处理促销活动的表面层
 */

@Controller
@Scope("prototype")
@Namespace("/")
@ParentPackage("json-default")
public class PromotionAction extends BaseAction<Promotion>{
	
	//定义属性驱动接收上传的文件
	private File titleImgFile;
	private String titleImgFileFileName;
	
     public void setTitleImgFileFileName(String titleImgFileFileName) {
		this.titleImgFileFileName = titleImgFileFileName;
	}

	public void setTitleImgFile(File titleImgFile) {
		this.titleImgFile = titleImgFile;
	}

	//注入业务层
	@Autowired
	private PromotionService  promotionService;
	
	
	//添加促销活动成功之后，跳回到促销活动的页面
	@Action(value="promotion_save",results={@Result(name="success",location="/pages/take_delivery/promotion.html",type="redirect")})
	public String save() throws IOException{
		//宣传图上传，数据表中保存宣传图保存的路径
		//存储图片文件的绝对地址
		String savePath = ServletActionContext.getServletContext().getRealPath("/upload/");
		
		//存储图片的相对路径,工程名+文件名
		String saveUrl=ServletActionContext.getRequest().getContextPath()+"/upload/";
		
		//生成随机的图片名，避免图片名重复
		UUID uuid=UUID.randomUUID();
		
		//拿到图片的扩展名
		String ext = titleImgFileFileName.substring(titleImgFileFileName.lastIndexOf("."));
		
		//将图片的名字用随机的数字换掉
		String randomFileName=uuid+ext;
		
		//保存图片,用绝对路径，保存到磁盘
		FileUtils.copyFile(titleImgFile, new File(savePath+"/"+randomFileName));
		 
		//将图片得相对路径保存到promotion实体的titleImg属性中
		model.setTitleImg(ServletActionContext.getRequest().getContextPath()+"/upload/"+randomFileName);
		
		//调用业务层，将数据保存到数据库中
		promotionService.save(model);
		
		
		return SUCCESS;
	}
	
	/**
	 * 促销活动后台分页功能
	 */
	
	@Action(value="promotion_pageQuery",results={@Result(name="success",type="json")})
	public String pageQuery(){
		
	//构造pageable分页查询参数,参数page,rows在action父类中已经获取，这里page是从0开始，所以要减一
	Pageable pageable=new PageRequest( page-1,rows);	
		
	//调用业务层完成操作
	Page<Promotion> pagedata=promotionService.pageQuery(pageable);
	
	//将 页面所需的total和rows存入值栈
	pushPageDataToValueStack(pagedata);
	
		return SUCCESS;
	}
	
}
